<template>
  <div class="invoice-abandon">
    <ListTab v-model="activeId" :tabs="tabList" :show-header="!showMobilePage" is-table @tabClick="queryClick" />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" style="display: flex;align-items: center;position: relative;margin-bottom: 16px;">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          is-show-config
          @filterTagStatus="filterTagStatus"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"/>
        <div class="current-user-action-box">
          <el-checkbox v-model="isMyPending" style="margin-right: 20px;" @change="queryClick">待我处理</el-checkbox>
          <el-checkbox v-model="isShowMe" @change="queryClick" >我发起的</el-checkbox>
          <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
        </div>
        <createBtn v-if="hasRouteAuth('invoice:abandon:create')" style="margin-right:10px;" @click.native="createData" />
        <MoreOpeator
          ref="moreOpeatorRef"
          :list="[
            { label: '批量抄送', handelClick: handleSendMsg },
            { label: '复制链接', handelClick: batchCopyLink }
          ]"
        />
      </div>
      <div v-loading="listLoading" style="min-height: 300px">
        <u-table
          v-if="list.total > 0"
          ref="tableRef"
          :data="list.items"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          use-virtual
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          class="fb-table"
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <u-table-column
            :fixed="selectFixed"
            align="center"
            type="selection"
            width="50"/>
          <u-table-column :min-width="handleTdWidth()" align="left" label="审批单号" label-class-name="diy-cell" class-name="diy-cell">
            <template slot-scope="scope" slot="header">
              <div class="diyHeader">{{ scope.column.label }}</div>
            </template>
            <template slot-scope="scope">
              <processSn :is-expedited="scope.row.isExpedited">
                <div v-if="scope.row.status !== 0" class="link" @click="toDetail(scope.row)">{{ scope.row.examineId ? handleSnNumber(scope.row.examineId) : '--' }}</div>
                <div v-else>{{ scope.row.examineId ? handleSnNumber(scope.row.examineId) : '--' }}</div>
              </processSn>
            </template>
          </u-table-column>
          <u-table-column align="left" label="作废说明" min-width="140">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.abandonRemark" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="纳税人名称" min-width="100">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.customerName" placement="top">
                <el-scrollbar slot="content">
                  <div style="max-width: 220px;max-height: 200px;" v-html="filterArr(scope.row.customerName)"/>
                </el-scrollbar>
                <div class="ellipsisOne">{{ scope.row.customerName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column :min-width="handleTdWidth(110,140)" align="right" label="含税金额(元)" prop="amount" sortable="custom">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.amount" :price="scope.row.amount/100" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="申请人" min-width="100">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposer" :user-id="scope.row.proposerId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="当前节点" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.currentNode" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="当前处理人" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.currentUser" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="状态" min-width="100">
            <template slot-scope="scope">
              <StatusText
                v-if="scope.row.status || scope.row.status===0"
                :color="['#406eff','#fd8546', 'red', '#999', '#31cc9c','#406eff'][scope.row.status]"
                :text="scope.row.status | signUpStatus" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="申请部门" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.deptName" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="100">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="160" prop="createTime" sortable="custom">
            <template slot-scope="scope">
              <div>{{ scope.row.createDate | format('YYYY/MM/DD') }}</div>
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
            <template slot-scope="scope">
              <div style="display:flex;">
                <div v-if="scope.row.status !== 0 && !showMobilePage" class="button-text br" @click="toDetail(scope.row)">查看</div>
                <MoreOpeator
                  :list="[
                    {
                      label: '查看',
                      handelClick: () => {toDetail(scope.row)},
                      auth: scope.row.status !== 0 && showMobilePage
                    },{
                      label: '复制',
                      handelClick: () => {handlerCreateNew(scope.row)},
                      disabled: scope.row.status === 0 || !hasRouteAuth('invoice:abandon:create')
                    },{
                      label: '编辑',
                      handelClick: () => {toEdit(scope.row)},
                      disabled: setEditDisable(scope.row)
                    },{
                      label: '删除',
                      handelClick: () => {btnDel(scope.row)},
                      disabled: setDelDisable(scope.row)
                    }
                  ]"
                >
                  <div v-if="!showMobilePage" slot="button" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                  <el-image v-else slot="button" :src="operateBtns" class="table-dropdown-img"/>
                </MoreOpeator>
              </div>
            </template>
          </u-table-column>
        </u-table>
        <EmptyPlaceholder v-else-if="!list.isInit" empty-text="暂无数据" mode="table" style="padding-bottom: 0;" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination class="pagination-area">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            @filterTagStatus="filterTagStatus"
            @handelClick="queryClick"
            @queryEmpty="queryEmpty">
            <div slot="checkGroup">
              <el-checkbox v-model="isMyPending" style="margin-right: 20px;" @change="queryClick">待我处理</el-checkbox>
              <el-checkbox v-model="isShowMe" @change="queryClick" >我发起的</el-checkbox>
              <el-checkbox v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
            </div>
          </FilterInput>
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="[
              { label: '批量抄送', handelClick: handleSendMsg },
              { label: '复制链接', handelClick: batchCopyLink }
            ]"
            show-mobile-icon
          />
          <createBtn v-if="hasRouteAuth('invoice:abandon:create')" mobile-table @click.native="createData"/>
        </template>
        <template v-else>
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <span style="flex:1;"/>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
      <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleBatchSender" />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import ListTab from '@/components/ListTab';
import createBtn from '@/components/Common/baseComponent/createBtn';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import { getDepartmentAll } from '@/api/config';
import { format } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { commonOptions } from '@/utils/tools';
import { getAbandonList, getAbandonTab, deleteAbandon } from '@/api/invoiceAbandon';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import tableSelections from '@/mixins/tableSelections';
import schedule from '@/mixins/schedule';
import copyLink from '@/mixins/copyLink';
// filter
import { expeditedOptions } from '@/filters/status';
import { energyStatus as signUpStatus } from '@/filters/status';
import { paramsAryToStr } from '@/utils/paramsFormat';
import { CURRENT_NODE_MODULE } from '@/utils/const';
import { PROCESS_TYPE } from '@/utils/const/process';
import axios from 'axios';
export default {
  components: { ListTab, createBtn, EmptyPlaceholder, MoreOpeator, DiversAuditorDialog },
  filters: {
    format,
    signUpStatus
  },
  mixins: [TableAdaptive, mobileTable, filterObjStoreMixin, copyLink, tableSelections, schedule],
  data() {
    return {
      activeId: -1,
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      tabList: [{
        id: -1,
        name: '全部'
      }],
      sortName: '',
      sortType: '',
      listLoading: false,
      paramsObj: {},
      deptTreeList: [],
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true,
      isShowMe: false,
      isMyApproval: false,
      isMyPending: false,
      cancelToken: null,
      arrayKeyArr: ['currentNode', 'deptId']
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      return [
        { keyword: 'examineId', name: '审批单号', type: 'input' },
        { keyword: 'customerName', name: '纳税人名称', type: 'input' },
        { keyword: 'abandonRemark', name: '作废说明', type: 'input' },
        { keyword: 'proposer', name: '申请人', type: 'input' },
        { keyword: 'creator', name: '创建人', type: 'input' },
        // { keyword: 'currentNode', name: '当前节点', type: 'input' },
        { keyword: 'currentUser', name: '当前处理人', type: 'input' },
        { keyword: 'comment', name: '评论', type: 'input' },
        { keyword: 'approvalComment', name: '审批意见', type: 'input' },
        { keyword: 'amount', name: '含税金额', type: 'inputRange' },
        { keyword: 'status', name: '状态', type: 'select', options: commonOptions },
        { keyword: 'deptId',
          name: '申请部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList
        },
        {
          keyword: 'currentNode',
          name: '当前节点',
          type: 'loadMoreSelect',
          valueName: 'name',
          directShow: true,
          multiple: true,
          extendParams: { type: CURRENT_NODE_MODULE.ABANDON },
          labelName: 'name',
          placeholder: '当前节点',
          searchkeyword: 'keyword',
          apiUrl: 'admin/common/currentNodes'
        },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        { keyword: 'createDate', name: '创建日期', timeType: 'daterange', type: 'rangeDate' }
      ];
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  created() {
    this.queryDeptTreeList();
  },
  beforeRouteEnter(to, from, next) {
    to.meta.isChange = from.name === 'invoiceAbandonDetail';
    next();
  },
  activated() {
    if (!this.$route.meta.isChange) {
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      // 当预设的默认筛选且为第一次进入页面时，不请求数据（会在 filterTool 组件进行筛选）
      if (!this.list.isInit || !hasDefaultPresetFilter) {
        this.paramsObj = {};
        this.activeId = -1;
        this.fetchData(true);
      }
    } else {
      this.fetchData();
    }
    this.queryDeptTreeList();
  },
  methods: {
    hasRouteAuth,
    getDetailLink(item) {
      if (!item.status) return null;
      return `${location.origin}#/businessPage/invoiceAbandonDetail?id=${item.id}&processId=${item.processId}`;
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      if (params.amount && params.amount.length === 2) {
        params.amountStart = params.amount[0] || params.amount[0] === 0 ? Number(params.amount[0]) : null;
        params.amountEnd = params.amount[1] || params.amount[1] === 0 ? Number(params.amount[1]) : null;
      }
      if (params.createDate && params.createDate.length === 2) {
        params.createDateStart = Math.round(params.createDate[0] / 1000);
        params.createDateEnd = Math.round(params.createDate[1] / 1000);
      }
      delete params.amount;
      delete params.createDate;
      paramsAryToStr(this.arrayKeyArr, params);
      params.isShowMe = this.isShowMe;
      params.isMyApproval = this.isMyApproval;
      params.isMyPending = this.isMyPending;
      params.page = this.page;
      params.perPage = this.perPage;
      params.tabStatus = this.activeId;
      params.sortType = this.sortType || '';
      params.sortName = this.sortName || '';
      return params;
    },
    fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source(); // 用于取消请求
      this.cancelToken = source;
      if (reset) {
        this.page = 1;
      }
      this.getTabList();
      const params = this.formatParams();
      this.listLoading = true;
      getAbandonList(params, source.token).then(res => {
        if (res.code === 200) {
          this.list = res.data;
        }
        this.list.isInit = false;
        this.listLoading = false;
      }, result => {
        this.list.isInit = false;
        this.listLoading = false;
      });
    },
    async getTabList() {
      try {
        const params = this.formatParams();
        const result = await getAbandonTab(params);
        if (result.code === 200) {
          this.tabList = result.data;
        }
      } catch (error) {
        this.tabList = [
          { id: -1, name: '全部', num: 0 }
        ];
        console.log(error);
      }
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.isShowMe = false;
      this.isMyApproval = false;
      this.isMyPending = false;
      this.fetchData(true);
    },
    createData() {
      this.$router.push({
        name: 'createInvoiceAbandon'
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    toEdit(item) {
      this.$router.push({
        name: 'editInvoiceAbandon',
        params: {
          id: item.id
        }
      });
    },
    toDetail(row) {
      this.filterObjStore(PROCESS_TYPE.ABANDON_INVOICE);
      this.$router.push({
        name: 'invoiceAbandonDetail',
        query: {
          id: row.id,
          processId: row.processId,
          fromList: 1
        }
      });
    },
    btnDel(data) {
      this.$confirm('是否确定删除？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        deleteAbandon(data.id).then(res => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.resetItemSelected(data.id);
          this.fetchData(true);
        }, result => {
          // this.$message.error(result.message);
        });
      }).catch(() => {
        return false;
      });
    },
    setEditDisable(data) {
      // 草稿才可以编辑
      return !(data.status === 0 && data.creatorId === this.userInfo.id);
    },
    setDelDisable(data) {
      const statusArr = [0, 2, 3, 5];// 草稿、已撤销、未过审、待提交
      return !(statusArr.includes(data.status) && (data.creatorId === this.userInfo.id || this.hasRouteAuth('invoice:abandon:delete')));// 除审批中和已完成状态且为创建人或者有删除权限
    },
    filterArr(str) {
      if (!str) return '--';
      try {
        const arr = str.split(',').join('</br>');
        return arr;
      } catch (error) {
        return str;
      }
    },
    handlerCreateNew(row) {
      const routeUrl = this.$router.resolve({
        name: 'editInvoiceAbandon',
        params: {
          id: row.id
        },
        query: {
          reapplyId: row.processId,
          createNew: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.table-list {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
  .current-user-action-box {
    position: absolute;
    left: 509px;
    top: 6px;
    display:flex;
    align-items:center;
  }
}
.link {
  cursor: pointer;
  color: #406eff;
}
</style>
